package leetcode;

import java.util.Arrays;

/**
 * 从长度为m的数组中找出连续n位之和最大的那一段
 *
 * @author 王霄
 * @date 2022/2/13 20:09
 */
public class Code001 {
    public static void main(String[] args) {
        int[] arr = {3, 4, 1, 2, 7, 6, 9, 8, 5};
        System.out.println(Arrays.toString(search(arr, 4)));
    }

    public static int[] search(int[] arr, int n) {
        if (arr.length < 1 || arr.length < n || n < 0) {
            throw new RuntimeException();
        }
        int maxIndex = 0;
        int maxSum = 0;
        for (int i = 0; i <= arr.length - n; i++) {
            int sum = 0;
            for (int j = 0; j < n; j++) {
                sum += arr[i + j];
            }
            if (sum > maxSum) {
                maxSum = sum;
                maxIndex = i;
            }
        }
        int[] maxArr = new int[n];
        System.arraycopy(arr, maxIndex, maxArr, 0, maxArr.length);
        return maxArr;
    }
}
